<?php

	//云存储百度POI
	function mapStorge($data,$func='create'){
	
		$map['ak']  = C("MAP_AK");
		$map['geotable_id'] = C("MAP_OUTLET_ID");
		$map['coord_type']  = 3;
	
		$url  = C("MAP_STORGE").$func;
		$map  = array_merge($map,$data);
		$json = curlPost($url,$map);
		return $json;
	}
	
	/**
	 * 记录系统API日志
	 * @param $content  操作内容
	 */
	function wapilog($content ='') {
		
		$model = M("ApiLog");
				
		$data['title']   = getApiName();
		$data['content'] = $content;
		$data['group']   = GROUP_NAME;
		$data['module']  = MODULE_NAME;
		$data['action']  = ACTION_NAME;
		$data['appid']   = APP_ID;

		$data['addid']   = I("addid","","intval");
		$data['addtime'] = time();

		//$model->add($data);
	}
	
	/**
	 * 记录核心API日志
	 * @param $content  操作内容
	 */
	function wuserlog($content ='', $table ='', $id =0) {
	
		$model = M("CustomLog");
			
		$data['title']   = getApiName();
		$data['content'] = $content;
		
		$data['group']   = GROUP_NAME;
		$data['module']  = MODULE_NAME;
		$data['action']  = ACTION_NAME;
		$data['tableid'] = $table;
		$data['dataid']  = $id;
		
		$data['company'] = I("company","","intval");
	  //$data['userid']  = I("userid","","intval");
		$data['customid']= I("customid","","intval");
		$data['addid']   = I("addid","","intval");
		$data['addtime'] = time();
	
		$model->add($data);
	}
	
	/**
	 * 获得API操作名称
	 */
	function getApiName(){
		
		$group  = GROUP_NAME;
		$module = MODULE_NAME;
		$action = ACTION_NAME;
		
		load("@.api");
		$nodes  = return_array(false,$group,$module,$action);
		return $nodes[getLang()];
	}
	/**
	 * 获取用户信息(id和类型)
	 * type Member(微网站会员) Memberwx(微信会员) Guest(游客)
	 */
	function getMember(){
	
		$memberId   = session(C('USER_AUTH_KEY'));
		$memberType = session(C('USER_AUTH_TYPE'));
		if(empty($memberId)){
				
			$memberId   = cookie("memberGuestId");
			$memberType = "Guest";
			if(empty($memberId)){
				ob_start();
				$memberId   = create_id("G");
				$memberType = "Guest";
				$expire     = C("COOKIE_KEEP_TIME");
				cookie("memberGuestId"  , $memberId  ,$expire);
				cookie("memberGuestType", $memberType,$expire);
			}
		}
		return array('id'=>$memberId,'type'=>$memberType);
	}

	/**
	 * 
	 * @param 收件人         $address
	 * @param 标题             $title
	 * @param 内容             $content
	 * @param 发送人名称  $fromname
	 * @param 发送人          $from
	 * @param 记录日志      $flag
	 * @param 附件              $attachment
	 */
	function sendMail($mail,$address,$title,$content,$fromname='',$from='',$flag=true, $attachment = null) {
		
		$fromname = empty($fromname) ? get_syscfig_key("emailSignal") : $fromname;
		$from     = empty($from)     ? get_syscfig_key("emailSend")   : $from;
		
		$mail ->setTo($address);
		$mail ->setFrom($from);
		$mail ->setSender($fromname);
		$mail ->setSubject($title);
		$mail ->setHtml($content);
	
		if(is_array($attachment)){
			foreach($attachment as $att){
				$mail ->addAttachment($att['savepath'].$att['savename'],$att['name']);
			}
		}
		
		$info = $mail ->send();
		
		if($flag){
			$map['title']   = $title;
			$map['content'] = $content;
			$map['email']   = $address;
			$map['status']  = $info[0];
			$map['feed']    = $info[1];
			$map['lang']    = LANG_SET;
			$map['addtime'] = time();
			M("EmailSendLog")->add($map);
		}

		return $info;
	}
	
	/**
	 * 创建邮件对象
	 */
	function createMail(){
		
		import("@.ORG.Email");
		$mail_type = get_syscfig_key("emailType");//C("MAIL_TYPE");
		$mail_host = get_syscfig_key("emailServer");//C("MAIL_HOST");
		$username  = get_syscfig_key("emailAccount");//C("MAIL_LOGINNAME");
		$password  = get_syscfig_key("emailPwd");//C("MAIL_PASSWORD");
		
		$mail = new Email($mail_type,$mail_host,$username,$password);
		
		return $mail;
	}
	
	/**
	 * 发送短信
	 * @param 手机号码(多个以逗号分割) $mobile
	 * @param 短信内容  $content
	 */
	function sendSms($url,$mobile,$content,$flag=true){
		
		/*
		$model = D("Tip");
		$info  = $model->checkSmsNum($mobile);
		if($info[0]){
			return $info = array(2,$flag[1]);
		}*/
		
		$url .= '&smsMob='.$mobile.'&smsText='.$content;
		//$url .= "&mobile=".$mobile."&content=".urlencode($content);
		/* if(function_exists('file_get_contents')){
			$flag = file_get_contents($url);
		}else{  exit($url); */
		$ch = curl_init();
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
		$res = trim(curl_exec($ch));
		curl_close($ch);
		//}
		
		if(intval($res)>0){
			$info = array(1,"Send success");
		}else{
			$info = array(2,L("sms_note_send_errorTip"));
		}
		
		if($flag){
			$map['content'] = $content;
			$map['mobile']  = $mobile;
			$map['status']  = $info[0];
			$map['feed']    = $info[1];
			D("Tip")->smsSendLog($map);
		}
		return $info;
	}
	
	/**
	 * 创建短信url
	 */
	function createMobile(){
		
		$sms_url = get_syscfig_key("smsurl");
		
		$app_id  = "?Uid=".get_syscfig_key("smsid");
		$app_key = "&Key=".get_syscfig_key("smskey");
		//http://sms.106jiekou.com/utf8/sms.aspx?account=用户账号&password=接口密码&mobile=号码&content=内容
		return $sms_url.$app_id.$app_key;
	}
	
	//根据手机号码获取用户编号
	function getUseridByMobile($mobile){
		
		$map['username'] = $mobile ;
		return M("Member")->where($map)->getField("id");
	}
	
	//过滤请求参数中不需要的参数
	function filterRestKey($_input){
		
		$filters = array("_sign"=>"","_URL_"=>"");
		return array_diff_key($_input, $filters);
	}
	
	//格式化输出优惠卷Attr信息
	function formatCouponAttr($attr,$type){
		
		$array = json_decode($attr,true);
	
		$calc  = C("COUPON_CALAC");
		$sale  = $calc[$type];
		
		$str = '';
		if($sale['isarray']&&is_array($sale)){
			$val = $sale['val'] ;
			$arr = $array[$type] ;
				
			$cou = count($arr[$val[0]]);
				
			$key = $arr[$val[0]] ;
			$vue = $arr[$val[2]] ;
		
			for($i=0;$i<$cou;$i++){
				if($key[$i] && $vue[$i]){
					$str .= $val[1].$key[$i].','.$val[3].$vue[$i]."<br>";
				}
			}
		}else{
			if($type == "discount"){
				$str = $sale[$type].'：'.$array[$type]."%";
			}else{
				$str = $sale[$type].'：'.$array[$type]."元";
			}
		}
		return $str;
	}
	
	
	/**
	 * 根据优惠领取编号,输入一个金额,计算改金额的优惠金额
	 * @param  int    $couponid
	 * @param  double $total
	 * @return double
	 */
	function calcCoupon($couponid,$total){
		
		$m['cid']= $couponid;
		$coupon  = D("CouponUserView");
		$view    = $coupon->where($m)->field("attr,type,title")->find();
		
		$type   = $view['type'];
		$attr   = json_decode($view['attr'],true);
		
		
		if(is_array($view)){
			//折扣优惠
			if($type == "discount"){
				$total = $total*$attr[$type]/100;
			}//抵现优惠
			elseif($type == "cash"){
				$total = $total-$attr[$type];
			}//满减优惠
			elseif($type=="fullcut"){
				$count = count($attr[$type]['full']);
	
				$key = $attr[$type]['full'] ;
				$vue = $attr[$type]['cut'] ;
				for($i=($count-1);$i>=0;$i--){
					if($total>=$key[$i]){
						$total = $total - $vue[$i];
						break;
					}
				}
			}//满折优惠
			elseif($type=="fulldiscount"){
				$count = count($attr[$type]['full']);
	
				$key = $attr[$type]['full'] ;
				$vue = $attr[$type]['discount'] ;
				for($j=($count-1);$j>=0;$j--){
					if($total>=$key[$j]){
						$total = $total*$vue[$j]/100;
						break;
					}
				}
			}
		}
		//$total = $total>=0?$total:0;
		return $total;
	}
	
	
	/**
	 * URL组装 支持不同URL模式
	 * @param string $url URL表达式，格式：'[分组/模块/操作#锚点@域名]?参数1=值1&参数2=值2...'
	 * @param string|array $vars 传入的参数，支持数组和字符串
	 * @param string $suffix 伪静态后缀，默认为true表示获取配置值
	 * @param boolean $redirect 是否跳转，如果设置为true则表示跳转到该URL地址
	 * @param boolean $domain 是否显示域名
	 * @return string
	 */
	function U($url='',$vars='',$suffix=true,$redirect=false,$domain=false) {
		// 解析URL
		$info   =  parse_url($url);
		$url    =  !empty($info['path'])?$info['path']:ACTION_NAME;
		if(isset($info['fragment'])) { // 解析锚点
			$anchor =   $info['fragment'];
			if(false !== strpos($anchor,'?')) { // 解析参数
				list($anchor,$info['query']) = explode('?',$anchor,2);
			}
			if(false !== strpos($anchor,'@')) { // 解析域名
				list($anchor,$host)    =   explode('@',$anchor, 2);
			}
		}elseif(false !== strpos($url,'@')) { // 解析域名
			list($url,$host)    =   explode('@',$info['path'], 2);
		}
		// 解析子域名
		if(isset($host)) {
			$domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
		}elseif($domain===true){
			$domain = $_SERVER['HTTP_HOST'];
			if(C('APP_SUB_DOMAIN_DEPLOY') ) { // 开启子域名部署
				$domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
				// '子域名'=>array('项目[/分组]');
				foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
					if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) {
						$domain = $key.strstr($domain,'.'); // 生成对应子域名
						$url    =  substr_replace($url,'',0,strlen($rule[0]));
						break;
					}
				}
			}
		}
	
		// 解析参数
		if(is_string($vars)) { // aaa=1&bbb=2 转换成数组
			parse_str($vars,$vars);
		}elseif(!is_array($vars)){
			$vars = array();
		}
		if(isset($info['query'])) { // 解析地址里面参数 合并到vars
			parse_str($info['query'],$params);
			$vars = array_merge($params,$vars);
		}
	
		// URL组装
		$depr = C('URL_PATHINFO_DEPR');
		if($url) {
			if(0=== strpos($url,'/')) {// 定义路由
				$route      =   true;
				$url        =   substr($url,1);
				if('/' != $depr) {
					$url    =   str_replace('/',$depr,$url);
				}
			}else{
				if('/' != $depr) { // 安全替换
					$url    =   str_replace('/',$depr,$url);
				}
				// 解析分组、模块和操作
				$url        =   trim($url,$depr);
				$path       =   explode($depr,$url);
				$var        =   array();
				$var[C('VAR_ACTION')]       =   !empty($path)?array_pop($path):ACTION_NAME;
				$var[C('VAR_MODULE')]       =   !empty($path)?array_pop($path):MODULE_NAME;
				if($maps = C('URL_ACTION_MAP')) {
					if(isset($maps[strtolower($var[C('VAR_MODULE')])])) {
						$maps    =   $maps[strtolower($var[C('VAR_MODULE')])];
						if($action = array_search(strtolower($var[C('VAR_ACTION')]),$maps)){
							$var[C('VAR_ACTION')] = $action;
						}
					}
				}
				if($maps = C('URL_MODULE_MAP')) {
					if($module = array_search(strtolower($var[C('VAR_MODULE')]),$maps)){
						$var[C('VAR_MODULE')] = $module;
					}
				}
				if(C('URL_CASE_INSENSITIVE')) {
					$var[C('VAR_MODULE')]   =   parse_name($var[C('VAR_MODULE')]);
				}
				if(!C('APP_SUB_DOMAIN_DEPLOY') && C('APP_GROUP_LIST')) {
					if(!empty($path)) {
						$group                  =   array_pop($path);
						$var[C('VAR_GROUP')]    =   $group;
					}else{
						if(GROUP_NAME != C('DEFAULT_GROUP')) {
							$var[C('VAR_GROUP')]=   GROUP_NAME;
						}
					}
					if(C('URL_CASE_INSENSITIVE') && isset($var[C('VAR_GROUP')])) {
						$var[C('VAR_GROUP')]    =  strtolower($var[C('VAR_GROUP')]);
					}
				}
			}
		}
	
		if(C('URL_MODEL') == 0) { // 普通模式URL转换
			$url        =   __APP__.'?'.http_build_query(array_reverse($var));
			if(!empty($vars)) {
				$vars   =   urldecode(http_build_query($vars));
				$url   .=   '&'.$vars;
			}
		}else{ // PATHINFO模式或者兼容URL模式
			if(isset($route)) {
				$url    =   __APP__.'/'.rtrim($url,$depr);
			}else{
				$url    =   __APP__.'/'.implode($depr,array_reverse($var));
			}
			if(!empty($vars)) { // 添加参数
				foreach ($vars as $var => $val){
					if('' !== trim($val))   $url .= $depr . $var . $depr . urlencode($val);
				}
			}
			if($suffix) {
				$suffix   =  $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
				if($pos = strpos($suffix, '|')){
					$suffix = substr($suffix, 0, $pos);
				}
				if($suffix && '/' != substr($url,-1)){
					$url  .=  '.'.ltrim($suffix,'.');
				}
			}
		}
		if(isset($anchor)){
			$url  .= '#'.$anchor;
		}
		if($domain) {
			$url   =  (is_ssl()?'https://':'http://').$domain.$url;
		}
		if($redirect) // 直接跳转URL
			redirect($url);
		else
			return $url;
	}
	
?>